//
//  DCChatInputView.m
//  xmppBase
//
//  Created by striby on 16/1/8.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCChatInputView.h"

static int textViewMargin = 4;
static DCChatInputView * instance;

typedef enum _DCVoiceInputState
{
    DCVoiceInputStateNone=0,
    DCVoiceInputStateReady=1,
    DCVoiceInputStateRecording=2,
    
}DCVoiceInputState;


@interface DCChatInputView()
{
    BOOL userWantToHideAllViews;
    
    
}


@property(nonatomic,strong)  DCEmojiBoardView * emoji;

@property(nonatomic,assign)  BOOL emojiViewVisible;

@property(nonatomic,assign)  BOOL extraViewVisible;

@property(nonatomic,assign)  DCVoiceInputState voiceInputState;

@property(nonatomic,strong)  UIView * voiceStateView;

@property(nonatomic,strong)  AVAudioRecorder * voiceRecord;

@property(nonatomic,strong)  NSTimer * voiceRecordTimer;

/**
 *  语音输入
 */
-(void)setInputTextViewForVoice;
/**
 *  正常文本输入
 */
-(void)setInputTextViewNormal;
@end

@implementation DCChatInputView
@synthesize emojiViewVisible;
@synthesize extraViewVisible;
@synthesize emoji;

+(DCChatInputView *)getCurrentInstance
{
    return instance;
}

+(DCChatInputView *)shareInstance
{
     
    
    static dispatch_once_t once ;
    
    dispatch_once(&once, ^{
        instance = [[self alloc]initWithFrame:CGRectZero];
        [instance setBaseUI];
    });
    
    
    [instance setInputTextViewNormal];
    instance.voiceInputState = DCVoiceInputStateNone;
    
    [instance.textInputView resignFirstResponder];
    instance.textInputView.text = @"";
    
    instance.emojiViewVisible=NO;
    instance.extraViewVisible = NO;
    
    instance.emoji=nil;
    instance.chatExtraView=nil;
    
    [instance.emojiBtn setImage:[UIImage imageNamed:@"chatting_biaoqing_btn_normal"] forState:UIControlStateNormal];
    
    return instance;
}

-(void)setBaseUI
{
    [self setFrame:CGRectMake(0, 0, DCDeviceWidth, toolBarHeight)];
    
    self.backgroundColor = [UIColor whiteColor];
    
    
    
    _voiceBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, toolBtnWidth, toolBtnWidth)];
    [_voiceBtn addTarget:self action:@selector(voiceBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_voiceBtn setImage:[UIImage imageNamed:@"chat_setmode_voice_btn_normal"] forState:UIControlStateNormal];
    
    [self addSubview:_voiceBtn];
    
    _textInputView = [[UITextView alloc]initWithFrame:CGRectMake(toolBtnWidth, textViewMargin, DCDeviceWidth-3*toolBtnWidth, toolBarHeight-textViewMargin*2)];
    _textInputView.delegate =self;
    
    _textInputView.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    _textInputView.scrollEnabled=NO;
    _textInputView.showsHorizontalScrollIndicator=NO;
    _textInputView.showsVerticalScrollIndicator=NO;
    _textInputView.layer.borderWidth = .4;
    _textInputView.layer.cornerRadius = 4;
    _textInputView.font=[UIFont systemFontOfSize:16];
    _textInputView.returnKeyType = UIReturnKeySend;
    [self addSubview:_textInputView];
    
    
    _emojiBtn = [[UIButton alloc]initWithFrame:CGRectMake(DCDeviceWidth-2*toolBtnWidth, 0, toolBtnWidth, toolBtnWidth)];
    [_emojiBtn addTarget:self action:@selector(emojiBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_emojiBtn setImage:[UIImage imageNamed:@"chatting_biaoqing_btn_normal"] forState:UIControlStateNormal];
    
    [self addSubview:_emojiBtn];
    
    _extraBtn = [[UIButton alloc]initWithFrame:CGRectMake(DCDeviceWidth-toolBtnWidth, 0, toolBtnWidth, toolBtnWidth)];
    [_extraBtn addTarget:self action:@selector(extraViewPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_extraBtn setImage:[UIImage imageNamed:@"chat_setmode_add_btn_normal"] forState:UIControlStateNormal];
    
    
    [self addSubview:_extraBtn];
    
    
    UIImageView * line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, .5)];
    [line setImage:[UIImage imageNamed:@"case_cell_Line"]];
    [self addSubview:line];
    
    
 
    

    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(UIKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(UIKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    
}

-(void)didSendMessage
{
    _textInputView.text = @"";
    
    
    float dis = self.frame.origin.y+self.frame.size.height;
    
    [_textInputView setFrame:CGRectMake(toolBtnWidth, textViewMargin, DCDeviceWidth-3*toolBtnWidth, toolBarHeight-textViewMargin*2)];
    
    [self setFrame:CGRectMake(0,dis-toolBarHeight, DCDeviceWidth, toolBarHeight)];
}


-(BOOL)isVoiceIsFirstResponder
{
    if (self.voiceRecord) {
        return YES;
    }
    return NO;
}

-(BOOL)isInputViewFirstResponder
{
    return _textInputView.isFirstResponder||emojiViewVisible||extraViewVisible||[self isVoiceIsFirstResponder];
}

#pragma mark - 隐藏所有输入

-(void)hideAllInputViews
{
     CGFloat druation = .25;
    
    userWantToHideAllViews = YES;
  
    
    if (emoji&&![_textInputView isFirstResponder]) {
        [emoji hideEmojiBoardWithDuration:druation isUsingAnination:YES animations:^{
         [self setFrame:CGRectMake(0, self.superview.bounds.size.height-self.bounds.size.height, DCDeviceWidth, self.bounds.size.height)];
            
            
            if (self.delegate) {
                if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                    [self.delegate DCChatInputViewFrameChanged];
                }
                
            }
            
        } completion:nil];
        
    }
    
    if (_chatExtraView&&![_textInputView isFirstResponder]) {
        [_chatExtraView hideExtraViewWithDuration:druation isUsingAnination:YES animations:^{
             [self setFrame:CGRectMake(0, self.superview.bounds.size.height-self.bounds.size.height, DCDeviceWidth, self.bounds.size.height)];
            
            if (self.delegate) {
                if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                    [self.delegate DCChatInputViewFrameChanged];
                }
                
            }
            
        } completion:nil];
    }

    
    emojiViewVisible=NO;
    extraViewVisible=NO;
    
    
    [self.textInputView resignFirstResponder];
    
    [self.emojiBtn setImage:[UIImage imageNamed:@"chatting_biaoqing_btn_normal"] forState:UIControlStateNormal];
    
    userWantToHideAllViews=NO;
    
    if (self.frame.origin.y!=self.superview.bounds.size.height-self.bounds.size.height) {
        [UIView animateWithDuration:druation animations:^{
            [self setFrame:CGRectMake(0, self.superview.bounds.size.height-self.bounds.size.height, DCDeviceWidth, self.bounds.size.height)];
        }];
        
    }
}

#pragma mark - 语音
-(void)voiceBtnPressed:(UIButton*)sender
{
    if (self.voiceInputState==DCVoiceInputStateNone) {
        
        
        [self hideAllInputViews];
        
        [self setInputTextViewForVoice];
        
        self.voiceInputState=DCVoiceInputStateReady;
    }
    else if(self.voiceInputState==DCVoiceInputStateReady)
    {
        
       
        [self setInputTextViewNormal];
        
        self.voiceInputState=DCVoiceInputStateNone;
        
        [self.textInputView becomeFirstResponder];
    }
    
    
    
}

-(void)setInputTextViewForVoice
{
       [_voiceBtn setImage:[UIImage imageNamed:@"chat_setmode_key_btn_normal"] forState:UIControlStateNormal];
    
    [_textInputView setHidden:YES];
    
    if (self.voiceInputView==nil) {
        self.voiceInputView = [[UIButton alloc]initWithFrame:_textInputView.frame];
        [self addSubview:self.voiceInputView];
        
        [_voiceInputView setTitle:@"按住通话" forState:UIControlStateNormal];
        [_voiceInputView setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _voiceInputView.layer.borderColor = [[UIColor lightGrayColor]CGColor];
        
        _voiceInputView.layer.borderWidth = .4;
        _voiceInputView.layer.cornerRadius = 4;
        
        
        [_voiceInputView addTarget:self action:@selector(voiceInputTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_voiceInputView addTarget:self action:@selector(voiceInputTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_voiceInputView addTarget:self action:@selector(voiceInputTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
        [_voiceInputView addTarget:self action:@selector(voiceInputMovedIn:) forControlEvents:UIControlEventTouchDragEnter];
        [_voiceInputView addTarget:self action:@selector(voiceInputMovedOut:) forControlEvents:UIControlEventTouchDragExit];
    }
    else
    {
        [_voiceInputView setHidden:NO];
    }
    
    
  
}

-(void)setInputTextViewNormal
{
     [_voiceBtn setImage:[UIImage imageNamed:@"chat_setmode_voice_btn_normal"] forState:UIControlStateNormal];
    
    if (self.voiceInputView) {
        [self.voiceInputView setHidden:YES];
    }
    
    [_textInputView setHidden:NO];
    
    
    [self audioStopRecordForUserCancled:NO];
    
    
}
#pragma mark 语音输入事件
-(void)voiceInputTouchDown:(UIButton*)sender
{
    sender.backgroundColor=[UIColor lightGrayColor];
    [sender setTitle:@"松开发送" forState:UIControlStateNormal];
    
    [self voiceStateViewCreate];
    
    self.voiceInputState = DCVoiceInputStateRecording;
}

-(void)voiceInputMovedOut:(UIButton*)sender
{
    sender.backgroundColor=[UIColor whiteColor];
    [sender setTitle:@"按住通话" forState:UIControlStateNormal];
    
    if(self.voiceStateView)
    {
        if ([self.voiceStateView viewWithTag:voiceStateLabelTag]) {
            UILabel * lbl = [self.voiceStateView viewWithTag:voiceStateLabelTag];
            lbl.text = @"松开手指，取消发送";
            lbl.backgroundColor = [UIColor redColor];
        }
        
        if ([self.voiceStateView viewWithTag:voiceImageViewTag]) {
            UIImageView * imageView = [self.voiceStateView viewWithTag:voiceImageViewTag];
            
            imageView.image = [UIImage imageNamed:@"voice_record_cancel"];
        }
        
        
        if (self.voiceRecordTimer) {
            if (self.voiceRecordTimer.isValid) {
                [self.voiceRecordTimer invalidate];
            }
        }
    }
}

-(void)voiceInputMovedIn:(UIButton*)sender
{
    sender.backgroundColor=[UIColor lightGrayColor];
    [sender setTitle:@"松开发送" forState:UIControlStateNormal];
    
    if(self.voiceStateView)
    {
        if ([self.voiceStateView viewWithTag:voiceStateLabelTag]) {
            UILabel * lbl = [self.voiceStateView viewWithTag:voiceStateLabelTag];
            lbl.text = @"向上滑动，取消发送";
            lbl.backgroundColor = [UIColor clearColor];
        }
        
        if (self.voiceRecordTimer) {
            if (!self.voiceRecordTimer.isValid) {
                [self.voiceRecordTimer invalidate];
                self.voiceRecordTimer=nil;
                self.voiceRecordTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(voicePowerChanged) userInfo:nil repeats:YES];

            }
        }
        
        [self voicePowerChanged];
    }
}

-(void)voiceInputTouchUpInside:(UIButton*)sender
{
    sender.backgroundColor=[UIColor whiteColor];
    [sender setTitle:@"按住通话" forState:UIControlStateNormal];
    
    [self voiceStateViewRemoveFromSuperView];
    
    [self audioStopRecordForUserCancled:NO];
}

-(void)voiceInputTouchUpOutside:(UIButton*)sender
{
    sender.backgroundColor=[UIColor whiteColor];
    [sender setTitle:@"按住通话" forState:UIControlStateNormal];
    
    [self voiceStateViewRemoveFromSuperView];
    
    [self audioStopRecordForUserCancled:YES];
}

#pragma mark 录音视图管理
-(void)voiceStateViewCreate
{
    if (self.voiceStateView==nil) {
        self.voiceStateView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, voiceInputWidth, voiceInputWidth)];
        
        self.voiceStateView.center = self.superview.center;
        
        
        self.voiceStateView.backgroundColor = [UIColor blackColor];
        
        self.voiceStateView.alpha=.7;
        
        self.voiceStateView.layer.cornerRadius=6;
        self.voiceStateView.layer.masksToBounds=YES;
        
        if (![self.voiceStateView viewWithTag:voiceImageViewTag]) {
            UIImageView * voiceImageView = [[UIImageView alloc]initWithFrame:CGRectMake((voiceInputWidth-voiceInputImageViewWidth)/2, (voiceInputWidth-voiceInputImageViewWidth)/2-voiceInputStateFontSize, voiceInputImageViewWidth, voiceInputImageViewWidth)];
            voiceImageView.tag = voiceImageViewTag;
            voiceImageView.image = [UIImage imageNamed:@"voice_volume0"];
            [self.voiceStateView addSubview:voiceImageView];
        }
        
        if (![self.voiceStateView viewWithTag:voiceStateLabelTag]) {
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(15, self.voiceStateView.bounds.size.height-35, self.voiceStateView.bounds.size.width-30, 20)];
            
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:voiceInputStateFontSize];
            label.text = @"向上滑动，取消发送";
            label.tag = voiceStateLabelTag;
            
            [self.voiceStateView addSubview:label];
        }
      
        
    }
   
    
    [self audioRecoreStartRecord];
    
    if (self.voiceRecordTimer==nil) {
        self.voiceRecordTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(voicePowerChanged) userInfo:nil repeats:YES];
      
    }
    
    [self.superview addSubview:self.voiceStateView];
    
    
}

-(void)voiceStateViewRemoveFromSuperView
{
    if (self.voiceStateView) {
        [self.voiceStateView removeFromSuperview];
    }
    
    
    
    if (self.voiceRecordTimer) {
        [self.voiceRecordTimer invalidate];
        self.voiceRecordTimer=nil;
    }
}

-(void)audioRecoreStartRecord
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
    
    NSString *path =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:[XMPPStream generateUUID]];
    path = [path stringByAppendingPathExtension:@"caf"];
    
    //配置Recorder，
    NSDictionary *recordSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey,
                                   [NSNumber numberWithInt:16],AVEncoderBitRateKey,
                                   [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
                                   [NSNumber numberWithFloat:44100.0],AVSampleRateKey,
                                   nil];
    
    NSURL *URL = [NSURL fileURLWithPath:path];
    
    __autoreleasing NSError * error ;
    
    _voiceRecord = [[AVAudioRecorder alloc] initWithURL:URL settings:recordSetting error:&error];
    _voiceRecord.delegate=self;
    _voiceRecord.meteringEnabled = YES;
    [_voiceRecord prepareToRecord];
    [_voiceRecord record];
    
    
    
    if (error) {
        NSLog(@"%@",error);
    }
}

-(void)audioStopRecordForUserCancled:(BOOL)isUserCanceled
{
    if (self.delegate) {
        if ([self.delegate respondsToSelector:@selector(DCChatVoiceInputRecored:isUserCanceled:)]) {
            if (_voiceRecord) {
                [_voiceRecord stop];
                
                 [self.delegate DCChatVoiceInputRecored:[[NSData alloc] initWithContentsOfURL:_voiceRecord.url]  isUserCanceled:isUserCanceled];
                
                _voiceRecord=nil;
            }
            
           
        }
    }
    
    self.voiceInputState = DCVoiceInputStateReady;
}

-(void)voicePowerChanged
{
    [_voiceRecord updateMeters];
    int power = [_voiceRecord averagePowerForChannel:0]+100;
    
    
    
    if (self.voiceStateView) {
        if ([self.voiceStateView viewWithTag:voiceImageViewTag]) {
            UIImageView * imageView = (UIImageView*)[self.voiceStateView viewWithTag:voiceImageViewTag];
            
            
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"voice_volume%d",power/20]];
        }
    }
    
    
}


#pragma mark - 附加功能
-(void)extraViewPressed:(UIButton*)sender
{
    if (self.voiceInputState!=DCVoiceInputStateRecording) {
        [self setInputTextViewNormal];
        self.voiceInputState = DCVoiceInputStateNone;
        
    }
    else
    {
        return;
    }
    
    
    
    
    [self.emojiBtn setImage:[UIImage imageNamed:@"chatting_biaoqing_btn_normal"] forState:UIControlStateNormal];
    
    if (!_chatExtraView) {
        _chatExtraView = [DCChatExtraView shareInstanceInView:self.superview];
        _chatExtraView.delegate=self.delegate;
        if (_extraItems) {
            [_chatExtraView setItems:_extraItems];
        }
        else
        {
            [_chatExtraView setItems:@[@{extraIcon:@"actionbar_picture_icon",extraName:@"相册"},@{extraIcon:@"actionbar_camera_icon",extraName:@"相机"},@{extraIcon:@"actionbar_location_icon",extraName:@"位置"},@{extraIcon:@"actionbar_picture_icon",extraName:@"相册"},@{extraIcon:@"actionbar_camera_icon",extraName:@"相机"},@{extraIcon:@"actionbar_picture_icon",extraName:@"相册"},@{extraIcon:@"actionbar_camera_icon",extraName:@"相机"},@{extraIcon:@"actionbar_picture_icon",extraName:@"相册"},@{extraIcon:@"actionbar_camera_icon",extraName:@"相机"}]];
        }
        
        [self.superview addSubview:_chatExtraView];
        
     
        
        
    }

    CGFloat druation = .25;
    
    if (extraViewVisible==NO) {
        [_textInputView resignFirstResponder];
         extraViewVisible = YES;
        [_chatExtraView showExtraViewWithDuration:druation isUsingAnination:YES animations:^{
            
            if (emojiViewVisible==NO) {
               [self setFrame:CGRectMake(0, self.superview.bounds.size.height-( self.bounds.size.height+chatExtraViewHeight), DCDeviceWidth, self.bounds.size.height)];
                
                
                if (self.delegate) {
                    if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                        [self.delegate DCChatInputViewFrameChanged];
                    }
                    
                }
            }
            
            emojiViewVisible=NO;
            [emoji hideEmojiBoardWithDuration:druation isUsingAnination:NO animations:nil completion:^(BOOL finished) {
                
            }];
            
            } completion:^(BOOL finished) {
                
                
               
            }];

    }
    else
    {
    
        [self.textInputView becomeFirstResponder];
        
        
    }
 
    
    
}

#pragma mark - 表情

-(void)emojiBtnPressed:(UIButton*)sender
{
    if (self.voiceInputState!=DCVoiceInputStateRecording) {
        [self setInputTextViewNormal];
        self.voiceInputState = DCVoiceInputStateNone;
    }
    else
    {
        return;
    }
    
    
    CGFloat druation = .2;
    
    if (emojiViewVisible==NO) {
          [_textInputView resignFirstResponder];
        
         [_emojiBtn setImage:[UIImage imageNamed:@"chat_setmode_key_btn_normal"] forState:UIControlStateNormal];
        
        if (extraViewVisible==NO) {
            [UIView animateWithDuration:druation animations:^{
                
             
                
                [self setFrame:CGRectMake(0, self.superview.bounds.size.height-( self.bounds.size.height+emojiBoardHeight), DCDeviceWidth, self.bounds.size.height)];
                
                
                
                if (self.delegate) {
                    if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                        [self.delegate DCChatInputViewFrameChanged];
                    }
                    
                }
            }completion:^(BOOL finished) {
                
              
            }];
        }
        else
        {
//            extraViewVisible=NO;
        }
    
        

            if (!emoji) {
                emoji = [DCEmojiBoardView defaultEmojiBoardInView:self.superview];
                emoji.delegate = self;
                [self.superview addSubview:emoji];
            }
            [emoji.superview bringSubviewToFront:emoji];
        
        emojiViewVisible = YES;
        
        extraViewVisible = NO;
        
        [emoji showEmojiBoardWithDuration:druation isUsingAnination:YES animations:^{
            if (_chatExtraView) {
                [_chatExtraView setFrame:emoji.frame];
            }
        } completion:^(BOOL finished) {

        }];

        
    }
    else
    {
        
      
        
        [_emojiBtn setImage:[UIImage imageNamed:@"chatting_biaoqing_btn_normal"] forState:UIControlStateNormal];
        
       
        [self.textInputView becomeFirstResponder];
            
          emojiViewVisible=NO;
        [emoji hideEmojiBoardWithDuration:druation isUsingAnination:YES animations:nil completion:^(BOOL finished) {
           
        }];
        
        

    }
    
    
   
}

-(void)emojiItemPressed:(UIButton *)sender
{
    if (sender.tag==EMOJI_TAG) {
        
        NSMutableString * str = [[NSMutableString alloc]initWithString: _textInputView.text];
        
        [str appendString:sender.currentTitle];
        _textInputView.text = str;
        [self textViewDidChange:_textInputView];
    }
    else if (sender.tag == SEND_TAG)
    {
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(DCChatInputViewSendTextMessage:)]) {
                [self.delegate DCChatInputViewSendTextMessage:_textInputView.text];
            }
        }
        
        [self didSendMessage];
    }
    else
    {
        NSString * newStr = @"";
        NSString *text = _textInputView.text;
        if (text.length>0) {
            
            if (text.length >3) {
                if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-1]]) {
                    newStr=[text substringToIndex:text.length-1];
                }else if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-2]]) {
                    newStr=[text substringToIndex:text.length-2];
                }else if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-3]]) {
                    newStr=[text substringToIndex:text.length-3];
                }else  if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-4]]) {
                    newStr=[text substringToIndex:text.length-4];
                }else{
                    newStr=[text substringToIndex:text.length-1];
                }
                
            }else if (text.length >2) {
                
                if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-1]]) {
                    newStr=[text substringToIndex:text.length-1];
                }else if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-2]]) {
                    newStr=[text substringToIndex:text.length-2];
                }else if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-3]]) {
                    newStr=[text substringToIndex:text.length-3];
                }else{
                    newStr=[text substringToIndex:text.length-1];
                }
            }else   if (text.length >1) {
                if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-1]]) {
                    newStr=[text substringToIndex:text.length-1];
                }else if ([DCEmojiBoardView stringContainsEmoji:[text substringFromIndex:text.length-2]]) {
                    newStr=[text substringToIndex:text.length-2];
                }else{
                    newStr=[text substringToIndex:text.length-1];
                }
                
            }else {
                
            }
            
            _textInputView.text=newStr;
            [self textViewDidChange:_textInputView];
        }
    }
    

}


#pragma mark - textview delegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(DCChatInputViewSendTextMessage:)]) {
                [self.delegate DCChatInputViewSendTextMessage:textView.text];
            }
        }
        
    
//        [textView resignFirstResponder];
        
        [self didSendMessage];
        
        return NO;
    }
    
   
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView
{
    CGSize size = [textView sizeThatFits:CGSizeMake(textView.bounds.size.width, MAXFLOAT)];
    
    if (size.height!=textView.bounds.size.height) {
        [self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y-(size.height-textView.bounds.size.height), self.bounds.size.width, size.height+2*textViewMargin)];
        [textView setFrame:CGRectMake(textView.frame.origin.x, textViewMargin, textView.bounds.size.width, size.height)];
        
        
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                [self.delegate DCChatInputViewFrameChanged];
            }
            
        }
        
    }

}

#pragma mark - 键盘
-(void)UIKeyboardWillShowNotification:(NSNotification*)noti
{
    
    [_emojiBtn setImage:[UIImage imageNamed:@"chatting_biaoqing_btn_normal"] forState:UIControlStateNormal];
   
    
   
    if (extraViewVisible== YES) {
        [emoji.superview sendSubviewToBack:emoji];
    }
    
    extraViewVisible=NO;
    emojiViewVisible=NO;
    
    
    
    CGRect  value =  [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSNumber *duration = [noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    

    
    [UIView animateWithDuration:duration.doubleValue animations:^{
        self.transform = CGAffineTransformIdentity;
        
        if (self.bindingTableView) {

        }
        
        if (self.emoji) {
            [self.emoji setFrame:CGRectMake(0, self.emoji.superview.bounds.size.height-value.size.height, self.emoji.bounds.size.width, self.emoji.bounds.size.height)];
        }
        
        if (self.chatExtraView) {
            [self.chatExtraView setFrame:CGRectMake(0, self.chatExtraView.superview.bounds.size.height-value.size.height, self.chatExtraView.bounds.size.width, self.chatExtraView.bounds.size.height)];
        }
        
        
        [self setFrame:CGRectMake(0, self.superview.bounds.size.height-self.bounds.size.height-value.size.height, DCDeviceWidth, self.bounds.size.height)];
        
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                [self.delegate DCChatInputViewFrameChanged];
            }
            
        }
    }completion:^(BOOL finished) {
        
    } ];
}

-(void)UIKeyboardWillHideNotification:(NSNotification*)noti
{
    
    NSNumber *duration = [noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
   
    if (userWantToHideAllViews) {
        

        userWantToHideAllViews=NO;
        [UIView animateWithDuration:duration.floatValue animations:^{
            [self setFrame:CGRectMake(0, self.superview.bounds.size.height-self.bounds.size.height, DCDeviceWidth, self.bounds.size.height)];
            
            if (emoji) {
                [emoji hideEmojiBoardWithDuration:0 isUsingAnination:NO animations:nil completion:nil];
            }
            
            if (_chatExtraView) {
                [_chatExtraView hideExtraViewWithDuration:0 isUsingAnination:NO animations:nil completion:nil];
            }
            
            if (self.delegate) {
                if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                    [self.delegate DCChatInputViewFrameChanged];
                }
                
            }

            
        }completion:^(BOOL finished) {
            
                  }];

        
        return;
    }
    
    
    extraViewVisible=NO;
    
 
    
    if (emojiViewVisible) {
        return;
    }
    
    if (extraViewVisible||_chatExtraView.frame.origin.y<_chatExtraView.superview.bounds.size.height) {
        return;
    }

    
    [UIView animateWithDuration:duration.doubleValue animations:^{
        self.transform = CGAffineTransformIdentity;
        
        
        if (self.chatExtraView) {
            [self.chatExtraView setFrame:CGRectMake(0, self.chatExtraView.superview.bounds.size.height-chatExtraViewHeight, self.chatExtraView.bounds.size.width, self.chatExtraView.bounds.size.height)];
        }
        
        
        if (emojiViewVisible==YES) {
           [self setFrame:CGRectMake(0, self.superview.bounds.size.height-self.bounds.size.height, DCDeviceWidth, self.bounds.size.height)];
        }
      

        
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(DCChatInputViewFrameChanged)]) {
                [self.delegate DCChatInputViewFrameChanged];
            }
            
        }
        
    }];

}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    if(self.voiceRecord)
    {
        [self.voiceRecord stop];
        self.voiceRecord=nil;
    }
    
    if (self.voiceRecordTimer) {
        [self.voiceRecordTimer invalidate];
        self.voiceRecordTimer=nil;
    }
}


@end
